<template>
  <!--日历-->
  <div class="container_calendar" @click.stop="stopProp">
    <div class="container_calendar_header" v-show="$store.state.calendarShow">
      <div class="year">
        <van-dropdown-menu :overlay="false">
          <van-dropdown-item
            ref = menuitem1
            :options="calendarYearOption"
            v-model="calendarYearValue"
            @change="changeCalendar"
            @opened="CalendarFilterScroll('year')"
             />
        </van-dropdown-menu>
      </div>
      <div class="month">
        <van-dropdown-menu :overlay="false">
          <van-dropdown-item
            ref = menuitem2
            :options="calendarMonthOption"
            v-model="calendarMonthValue"
            @change="changeCalendar"
            @opened="CalendarFilterScroll('month')"
             />
        </van-dropdown-menu>
      </div>
      <div @click="changeCalendar('pre')">上一月</div>
      <div @click="changeCalendar('next')">下一月</div>
      <div @click="changeCalendar('now')">返回今日</div>
      <div @click="showImg()">
        <img src="../../../assets/static/image/dz/ds_icon.png" alt="" style="width: 18px; height: 18px;margin-right: 10px" />
      </div>

    </div>
    <template v-if="$store.state.calendarShow">
      <van-calendar
        title="日历"
        v-model="$store.state.calendarShow"
        ref="homeCalendar"
        :min-date="calendarMinDate"
        :max-date="calendarMaxDate"
        :formatter="calendarFormatter"
        position="top"
        :poppable="true"
        :show-confirm="false"
        color="#da1f0c"
        :readonly="false"
        :default-date="defaultDate"
        :style="{ height: '400px' }"
        @confirm="onConfirm"
      />
    </template>
  </div>
</template>

<script>
import Calendar from '@/utils/calendar.js'
import {mapState} from "vuex";
import API from "@/api/api-chat-list";
import {setCustomBubble, setQueryTaskList} from "@/utils/setChatStoreData";
import slidingScrollBar from "@/utils/slidingScrollBar";
import dayjs from "dayjs";
const isBetween = require('dayjs/plugin/isBetween')
dayjs.extend(isBetween)

const INTERVAL_YEAR = 10; // 日历年份最大年份和最小年份的取值间隔
const CURRENT_DATE = dayjs(); // 初始化日期

export default {
        name: "Calendar",
        data() {
          return {
            calendarMinDate: CURRENT_DATE.subtract(INTERVAL_YEAR,'year').startOf('year').startOf('month').toDate(),  // 日历最小时间
            calendarMaxDate: CURRENT_DATE.add(INTERVAL_YEAR,'year').endOf('year').endOf('month').toDate(),  //  日历最大时间
            calendarYearValue: 0,  // 日历选择年份
            calendarYearOption: [], // 日历年份
            calendarMonthValue: 0,  //  日历选择月份
            calendarMonthOption: [], // 日历月份
            holiday: {},  // 节假日日期
            defaultDate:new Date(),
            date: CURRENT_DATE.format('YYYY-MM-DD'), //当前年月日
            date1: null, //当前年月
            formatter: this.calendarFormatter,
          }
        },
        methods: {
          // 日历节气节假日格式化，会议，政治生日，待办
          calendarFormatter(day) {

            const _time = new Date(day.date);
            const y = _time.getFullYear();
            const m = _time.getMonth() + 1;
            const d = _time.getDate();
            const w = _time.getDay();
            const info = Calendar.solar2lunar(y, m, d);

            const time = dayjs(_time);
            const days = dayjs();
            const startDate = days.subtract(1,'month').startOf('month');
            const endDate = days.add(1,'month').endOf('month');
            //   改变周六周日显示颜色
            let className = w === 0 || w === 6 ? "weekendRed " : "";
            let topMark = "";

            // 判断当天是否有会议（显示内容：会、不显示）
            topMark += this.$store.state.meetingInfoMap.has(dayjs(_time).format('YYYY-MM-DD')) ?
              '会\xa0\xa0\xa0\xa0' : '\xa0\xa0\xa0\xa0\xa0\xa0';


            // 判断当前日期是否是当前月份前后一个月的日期，如果是，则做班休逻辑判断；否则，直接显示空内容
            if (dayjs(time).isBetween(startDate, endDate, 'day', '[]')) {

              // 判断当天标记显示（显示内容：班、休、不显示），flag判断当前日期是否是节假日
              const flag = this.holiday?.data.includes(info.date);

              if (w === 0 || w === 6) {
                topMark += flag ? '\xa0\xa0' : '班';
              } else {
                topMark += flag ? '休' : '\xa0\xa0';
              }
            }

            if (_time.toDateString() === new Date().toDateString()) {
              className += "calendarToday ";
            }
            day.topInfo = topMark;

            //政治生日，待办
            return this.calendarFormatterBottom(day,info,className);
          },
          //日历日期下面 政治生日 和 待办 显示处理
          calendarFormatterBottom(day,info,className) {
            let mark = "";
            // 员工政治生日标记
            if (this.$store.state.userInfo?.partyUser?.partyDate  &&
              this.$store.state.userInfo.partyUser.partyDate.includes(info.partDate)) {
              className += this.date.includes(info.partDate)  ? 'partyDate1' : 'partyDate' ;
              mark += '\xa0';
            }
            // 待办标记
            if(this.$store.state.workSubTasks?.includes(info.date)){
              className += this.date !== info.date ? 'todo' : '';
              mark += "待办";
            }
            //   优先级:党员生日、待办>节日>节气
            day.bottomInfo = mark !== '' ? mark : info.festival || info.Term;
            day.className = className;
            return day;
          },
          //  生成日历数据
          async changeCalendar(type) {
            this.$refs.menuitem1.toggle(false);
            this.$refs.menuitem2.toggle(false);
            let date = 1;
            if (type === 'now') {
              const nowDate = new Date();
              this.calendarYearValue = nowDate.getFullYear();
              this.calendarMonthValue = nowDate.getMonth();
              this.defaultDate = new Date();
              date = nowDate.getDate();
            } else if (type === 'pre') {
              this.calendarMonthValue -= 1;
              if (this.calendarMonthValue < 0) {
                this.calendarMonthValue = 11;
                this.calendarYearValue -= 1;
              }
            } else if (type === 'next') {
              this.calendarMonthValue += 1;
              if (this.calendarMonthValue > 11) {
                this.calendarMonthValue = 0;
                this.calendarYearValue += 1;
              }
            }
            const _date = new Date(this.calendarYearValue, this.calendarMonthValue, date);
            this.$refs.homeCalendar.scrollToDate(_date);
          },
          // 日历跳转至指定时间 默认：切换至当前筛选下时间，pre：切换至上个月， next：切换至下个月， now：切换至当前时间
          calendarDataCreate() {
            this.calendarYearValue = new Date().getFullYear();

            const nowDate = dayjs();
            // 日历起始年份
            const startYear = nowDate.subtract(INTERVAL_YEAR,'year').year();
            // 日历最后年份
            const endYear = nowDate.add(INTERVAL_YEAR,'year').year();
            this.calendarYearOption = Array.from({length:endYear - startYear + 1},
              (v,i) => ({text: startYear + i + "年",value: startYear + i}));
            this.calendarMonthValue = new Date().getMonth();
            // 日历起始月份
            const startMonth = 1;
            // 日历最后月份
            const endMonth = 12;
            this.calendarMonthOption = Array.from({length:endMonth - startMonth + 1},
              (v,i) => ({text: startMonth + i + "月",value: startMonth + i - 1 }));
          },
          // 将日历筛选下拉框滚动至可视范围内 year：滚动年份 month：滚动月份
          CalendarFilterScroll(type) {
            if (type === 'year') {
              this.$refs.menuitem2.toggle(false);
              // 年份滚动至相应位置
              document.querySelector('.year .van-popup').scrollTop =
                document.querySelector('.year .van-dropdown-item__option--active').offsetTop;
            } else if (type === 'month') {
              this.$refs.menuitem1.toggle(false);
              // 月份滚动至相应位置
              document.querySelector('.month .van-popup').scrollTop =
                document.querySelector('.month .van-dropdown-item__option--active').offsetTop;
            }
          },
          // 获取节假日日期
          async getHoliday(year,month) {
            const date = dayjs().set('year',year).set('month',month);

            // 上个月第一天日期
            const startDate = date.subtract(2,'month').startOf("month").format('YYYY-MM-DD');
            // 下个月最后一天日期
            const endDate = date.endOf("month").format('YYYY-MM-DD');
            const param = {
              startDate,
              endDate
            };
            this.holiday = await API.getHolidays(param);
          },
          onConfirm(date){
            const d = dayjs(date).format('YYYY-MM-DD');
            const partyDate = dayjs(date).format('MM-DD');
            this.$store.state.chooseDate = dayjs(date);
            let flag = true;

            // 待办判断
            if (this.$store.state.workSubTasks?.includes(d)) {
              const dom = document.getElementById('home_con');
              this.$store.commit('setRhScrollTop',dom.scrollTop);
              this.$store.commit('setRhPlate','ZB');
              this.$nextTick(() => {
                //滚动到以前记录的位置
                const sTop = this.$store.state.rhScrollTop['ZB'];
                slidingScrollBar( sTop, 'instant');
              });

              setQueryTaskList(this, '待办工单', 'TODO_TASK');
              flag = false;
            }

            // 政治生日判断
            if(this.$store.state.userInfo?.partyUser?.partyDate  &&
              this.$store.state.userInfo?.partyUser?.partyDate.includes(partyDate)){
              const param = {
                "type": 'text',
                "data": "这是您的政治生日!"
              }
              setCustomBubble(this, param);
              this.defaultDate=new Date();
              flag = false;
            }

            // 会议判断
            if(this.$store.state.meetingInfoMap.has(d)){
              const meetings = this.$store.state.meetingInfoMap.get(d).map(meetingInfo => {
                return `会议名称：${meetingInfo.meetingTitle} <br />会议时间：${meetingInfo.meetingDate}<br />
                          会议地点：${meetingInfo.meetingAddress}<br />会议内容：${meetingInfo.meetingContent}<br />`;
              }).join("<br />");

              const param = {
                "type": 'meeting',
                "data": meetings
              }
              setCustomBubble(this, param);
              this.defaultDate = new Date();
              flag = false;
            }

            this.$store.commit('setCalendarShow', flag);
          },
          showImg() {

            this.$store.state.imgDisplay = true;
          },
          // 阻止冒泡
          stopProp() {
            return true;
          }
        },
        computed: {
          ...mapState(['rhPlate','questionsAnswersData']),
        },
        updated() {
          // 重置日历筛选功能的日期内容
          if(!this.$store.state.calendarShow){
            this.calendarMonthValue = new Date().getMonth();
            this.calendarYearValue = new Date().getFullYear();
            // 初始化日历节假日时间段，下次打开页面时使用
            // this.getHoliday(new Date().getFullYear(),new Date().getMonth() + 1);
          }
        },
        created() {
          this.getHoliday(new Date().getFullYear(),new Date().getMonth() + 1);
          this.calendarDataCreate();
        }
    }
</script>

<style scoped>
  @import url('~@/assets/css/homeCalendar/index.css');
</style>
